﻿using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Xml;

namespace SharePoint.Desktop.Explorer
{
    [ToolboxItemAttribute(false)]
    public class Explorer : WebPart, IWebPartPageComponentProvider
    {
        private string contextualTab = @"
        <ContextualGroup Color=""DarkBlue""
         Command=""SPDesktopContextualTab.EnableContextualGroup""
         Id=""Ribbon.SPDesktopContextualTabGroup""
         Title=""SharePoint Desktop""
         Sequence=""502""
         ContextualGroupId=""SPDesktopContextualTabGroup"">
          <Tab
              Id=""Ribbon.SPDesktopCustomTab""
              Title=""SharePoint Explorer""
              Description=""SharePoint Desktop Explorer custom tab""
              Command=""SPDesktopContextualTab.EnableCustomTab""
              Sequence=""501"">
            <Scaling
              Id=""Ribbon.SPDesktopCustomTab.Scaling"">
              <MaxSize
                Id=""Ribbon.SPDesktopCustomTab.MaxSize""
                GroupId=""Ribbon.SPDesktopCustomTab.SPDesktopCustomGroup""
                Size=""OneLargeTwoMedium""/>
              <Scale
                Id=""Ribbon.SPDesktopCustomTab.Scaling.CustomTabScaling""
                GroupId=""Ribbon.SPDesktopCustomTab.SPDesktopCustomGroup""
                Size=""OneLargeTwoMedium"" />
            </Scaling>
            <Groups Id=""Ribbon.SPDesktopCustomTab.Groups"">
              <Group
                Id=""Ribbon.SPDesktopCustomTab.SPDesktopCustomGroup""
                Description=""SPDesktop group""
                Title=""Browsing""
                Command=""SPDesktopContextualTab.EnableCustomGroup""
                Sequence=""52""
                Template=""Ribbon.Templates.SPDesktopTemplate"">
                <Controls
                  Id=""Ribbon.SPDesktopCustomTab.SPDesktopCustomGroup.Controls"">
                  <Button
                    Id=""Ribbon.SPDesktopCustomTab.SPDesktopCustomGroup.Up""
                    Command=""SPDesktopContextualTab.UpCommand""
                    Sequence=""15""
                    Description=""1 level up in explorer""
                    LabelText=""Up""
                    Image32by32=""/_layouts/images/SharePoint.Desktop/upIcon32.png""
                    Image16by16=""/_layouts/images/SharePoint.Desktop/upIcon16.png"" 
                    TemplateAlias=""cust1""/>
                  <Button
                    Id=""Ribbon.SPDesktopCustomTab.SPDesktopCustomGroup.Desktop""
                    Command=""SPDesktopContextualTab.DesktopCommand""
                    Sequence=""16""
                    Description=""Go to desktop""
                    LabelText=""Desktop""
                    Image32by32=""/_layouts/images/SharePoint.Desktop/desktopIcon32.png""
                    Image16by16=""/_layouts/images/SharePoint.Desktop/desktopIcon16.png"" 
                    TemplateAlias=""cust2""/>
                </Controls>
              </Group>
              <Group
                Id=""Ribbon.SPDesktopCustomTab.SPDesktopCustomGroup""
                Description=""This is a custom group!""
                Title=""Clipboard""
                Command=""SPDesktopContextualTab.EnableCustomGroup""
                Sequence=""53""
                Template=""Ribbon.Templates.SPDesktopTemplate"">
                <Controls
                  Id=""Ribbon.SPDesktopCustomTab.SPDesktopCustomGroup.Controls"">
                  <Button
                    Id=""Ribbon.SPDesktopCustomTab.SPDesktopCustomGroup.Copy""
                    Command=""SPDesktopContextualTab.CopyCommand""
                    Sequence=""20""
                    Description=""Copy item""
                    LabelText=""Copy""
                    Image32by32=""/_layouts/images/SharePoint.Desktop/copyIcon32.png""
                    Image16by16=""/_layouts/images/SharePoint.Desktop/copyIcon16.png"" 
                    TemplateAlias=""cust1""/>
                  <Button
                    Id=""Ribbon.SPDesktopCustomTab.SPDesktopCustomGroup.Cut""
                    Command=""SPDesktopContextualTab.CutCommand""
                    Sequence=""21""
                    Description=""Cut item""
                    LabelText=""Cut""
                    Image32by32=""/_layouts/images/SharePoint.Desktop/cutIcon32.png""
                    Image16by16=""/_layouts/images/SharePoint.Desktop/cutIcon16.png"" 
                    TemplateAlias=""cust2""/>
                  <Button
                    Id=""Ribbon.SPDesktopCustomTab.SPDesktopCustomGroup.Paste""
                    Command=""SPDesktopContextualTab.PasteCommand""
                    Sequence=""22""
                    Description=""Paste item""
                    LabelText=""Paste""
                    Image32by32=""/_layouts/images/SharePoint.Desktop/pasteIcon32.png""
                    Image16by16=""/_layouts/images/SharePoint.Desktop/pasteIcon16.png"" 
                    TemplateAlias=""cust3""/>
                </Controls>
              </Group>
                <Group
                Id=""Ribbon.SPDesktopCustomTab.SPDesktopCustomGroup""
                Description=""This is a custom group!""
                Title=""Item Actions""
                Command=""SPDesktopContextualTab.EnableCustomGroup""
                Sequence=""54""
                Template=""Ribbon.Templates.SPDesktopTemplate"">
                <Controls
                  Id=""Ribbon.SPDesktopCustomTab.SPDesktopCustomGroup.Controls"">
                  <Button
                    Id=""Ribbon.SPDesktopCustomTab.SPDesktopCustomGroup.Edit""
                    Command=""SPDesktopContextualTab.EditCommand""
                    Sequence=""30""
                    Description=""Edit item properties""
                    LabelText=""Edit""
                    Image32by32=""/_layouts/images/SharePoint.Desktop/editIcon32.png""
                    Image16by16=""/_layouts/images/SharePoint.Desktop/editIcon16.png"" 
                    TemplateAlias=""cust1""/>
                  <Button
                    Id=""Ribbon.SPDesktopCustomTab.SPDesktopCustomGroup.CheckIn""
                    Command=""SPDesktopContextualTab.CheckInCommand""
                    Sequence=""31""
                    Description=""Check in item""
                    LabelText=""Check In""
                    Image32by32=""/_layouts/images/SharePoint.Desktop/checkIn32.png""
                    Image16by16=""/_layouts/images/SharePoint.Desktop/checkIn16.png"" 
                    TemplateAlias=""cust2""/>
                  <Button
                    Id=""Ribbon.SPDesktopCustomTab.SPDesktopCustomGroup.CheckOut""
                    Command=""SPDesktopContextualTab.CheckOutCommand""
                    Sequence=""32""
                    Description=""Check out item""
                    LabelText=""Check Out""
                    Image32by32=""/_layouts/images/SharePoint.Desktop/checkOut32.png""
                    Image16by16=""/_layouts/images/SharePoint.Desktop/checkOut16.png"" 
                    TemplateAlias=""cust3""/>
                  <Button
                    Id=""Ribbon.SPDesktopCustomTab.SPDesktopCustomGroup.Delete""
                    Command=""SPDesktopContextualTab.DeleteCommand""
                    Sequence=""33""
                    Description=""Delete item""
                    LabelText=""Delete""
                    Image32by32=""/_layouts/images/SharePoint.Desktop/deleteIcon32.png""
                    Image16by16=""/_layouts/images/SharePoint.Desktop/deleteIcon16.png"" 
                    TemplateAlias=""cust4""/>
                </Controls>
              </Group>
              <Group
                Id=""Ribbon.SPDesktopCustomTab.SPDesktopCustomGroup""
                Description=""This is a custom group!""
                Title=""Add Item""
                Command=""SPDesktopContextualTab.EnableCustomGroup""
                Sequence=""55""
                Template=""Ribbon.Templates.SPDesktopTemplate"">
                <Controls
                  Id=""Ribbon.SPDesktopCustomTab.SPDesktopCustomGroup.Controls"">
                  <Button
                    Id=""Ribbon.SPDesktopCustomTab.SPDesktopCustomGroup.Upload""
                    Command=""SPDesktopContextualTab.UploadCommand""
                    Sequence=""41""
                    Description=""Upload new item""
                    LabelText=""Upload""
                    Image32by32=""/_layouts/images/SharePoint.Desktop/uploadIcon32.png""
                    Image16by16=""/_layouts/images/SharePoint.Desktop/uploadIcon16.png"" 
                    TemplateAlias=""cust1""/>
                  <Button
                    Id=""Ribbon.SPDesktopCustomTab.SPDesktopCustomGroup.NewFolder""
                    Command=""SPDesktopContextualTab.NewFolderCommand""
                    Sequence=""42""
                    Description=""Create new Folder""
                    LabelText=""New Folder""
                    Image32by32=""/_layouts/images/SharePoint.Desktop/newfolderIcon32.png""
                    Image16by16=""/_layouts/images/SharePoint.Desktop/newfolderIcon16.png"" 
                    TemplateAlias=""cust2""/>
                </Controls>
              </Group>
            </Groups>
          </Tab>
   </ContextualGroup>";

        private string contextualTabTemplate = @"
          <GroupTemplate Id=""Ribbon.Templates.SPDesktopTemplate"">
            <Layout
              Title=""OneLargeTwoMedium"" LayoutTitle=""OneLargeTwoMedium"">
              <Section Alignment=""Top"" Type=""OneRow"">
                <Row>
                  <ControlRef DisplayMode=""Large"" TemplateAlias=""cust1"" />
                  <ControlRef DisplayMode=""Large"" TemplateAlias=""cust2"" />
                  <ControlRef DisplayMode=""Large"" TemplateAlias=""cust3"" />
                  <ControlRef DisplayMode=""Large"" TemplateAlias=""cust4"" />
                </Row>
              </Section>
              <Section Alignment=""Top"" Type=""TwoRow"">
                <Row>
                  <ControlRef DisplayMode=""Medium"" TemplateAlias=""cust5"" />
                </Row>
                <Row>
                  <ControlRef DisplayMode=""Medium"" TemplateAlias=""cust6"" />
                </Row>
              </Section>
            </Layout>
          </GroupTemplate>";

        private const string JQueryScript = "jquery.js";
        private const string JQueryScriptKey = "jquery";

        private const string JQueryUIScript = "jquery-ui.js";
        private const string JQueryUIScriptKey = "jquery-ui";

        private const string ExplorerScript = "sharepoint.desktop.explorer.js";
        private const string ExplorerScriptKey = "sharepoint.desktop.explorer";

        private const string IncludeScriptFormat = @"<script language=""{0}"" src=""{1}{2}""></script>";
        private const string location = "/_layouts/SharePoint.Desktop/";

        private string doctypes = "pdf:pdf.png";
        private string columns = "4";

        [WebBrowsable]
        [WebDisplayName("Doctypes")]
        [WebDescription("Additional Doctype Images")]
        [Category("SharePoint Explorer")]
        [Personalizable(PersonalizationScope.Shared)]
        public string Doctypes
        {
            get
            {
                return doctypes;
            }

            set
            {
                doctypes = value;
            }
        }

        [WebBrowsable]
        [WebDisplayName("Columns")]
        [WebDescription("Number of columns")]
        [Category("SharePoint Explorer")]
        [Personalizable(PersonalizationScope.Shared)]
        public string Columns
        {
            get
            {
                return columns;
            }

            set
            {
                columns = value;
            }
        }

        public Explorer()
        {
            this.PreRender += new EventHandler(Explorer_PreRender);
        }

        void Explorer_PreRender(object sender, EventArgs e)
        {
            //base.OnPreRender(e);

            this.AddContextualTab();

            if (!Page.ClientScript.IsClientScriptBlockRegistered("SPDesktopContextualTabWebPart"))
            {
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "SPDesktopContextualTabWebPart", this.DelayScript);
            }

            if (!Page.ClientScript.IsClientScriptBlockRegistered(JQueryScriptKey))
            {
                string includeScript = String.Format(IncludeScriptFormat, "javascript", location, JQueryScript);
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), JQueryScriptKey, includeScript);
            }

            if (!Page.ClientScript.IsClientScriptBlockRegistered(JQueryUIScriptKey))
            {
                string includeScript = String.Format(IncludeScriptFormat, "javascript", location, JQueryUIScript);
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), JQueryUIScriptKey, includeScript);
            }

            if (!Page.ClientScript.IsClientScriptBlockRegistered(ExplorerScriptKey))
            {
                string includeScript = String.Format(IncludeScriptFormat, "javascript", location, ExplorerScript);
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), ExplorerScriptKey, includeScript);
            }

            CssLink cssLink = new CssLink();
            cssLink.DefaultUrl = location + "sharepoint.desktop.css";
            Page.Header.Controls.Add(cssLink);

        }

        protected override void CreateChildControls()
        {  
        }

        protected override void Render(HtmlTextWriter writer)
        {
            writer.Write("<div id='sharepoint_explorer'>");
            writer.Write("<input id='doctypes' type='hidden' value='" + doctypes + "' />");
            writer.Write("<input id='columns' type='hidden' value='" + columns + "' />");
            writer.Write("<div id='sharepoint_explorer_main'/>");
            writer.Write("</div>");

            base.Render(writer);
        }

        public WebPartContextualInfo WebPartContextualInfo
        {
            get
            {
                WebPartContextualInfo info = new WebPartContextualInfo();
                WebPartRibbonContextualGroup contextualGroup = new WebPartRibbonContextualGroup();
                WebPartRibbonTab ribbonTab = new WebPartRibbonTab();

                //Create the contextual group object and initialize its values.
                contextualGroup.Id = "Ribbon.SPDesktopContextualTabGroup";
                contextualGroup.Command = "SPDesktopContextualTab.EnableContextualGroup";
                contextualGroup.VisibilityContext = "SPDesktopContextualTab.CustomVisibilityContext";

                //Create the tab object and initialize its values.
                ribbonTab.Id = "Ribbon.SPDesktopCustomTab";
                ribbonTab.VisibilityContext = "SPDesktopContextualTab.CustomVisibilityContext";

                //Add the contextual group and tab to the WebPartContextualInfo.
                info.ContextualGroups.Add(contextualGroup);
                info.Tabs.Add(ribbonTab);
                info.PageComponentId = SPRibbon.GetWebPartPageComponentId(this);
                
                return info;
            }
        }

        public string DelayScript
        {
            get
            {
                string webPartPageComponentId = SPRibbon.GetWebPartPageComponentId(this);
                return @"
                <script type=""text/javascript"">
                //<![CDATA[
                function _addCustomPageComponent()
                {
                    var _customPageComponent = new SPDesktopContextualTabWebPart.CustomPageComponent('" + webPartPageComponentId + @"');
                    SP.Ribbon.PageManager.get_instance().addPageComponent(_customPageComponent);
                }
                function _registerCustomPageComponent()
                {
                    SP.SOD.registerSod(""sharepoint.desktop.contextualtab.js"", ""\/_layouts\/SharePoint.Desktop\/sharepoint.desktop.contextualtab.js"");
                    SP.SOD.executeFunc(""sharepoint.desktop.contextualtab.js"", ""SPDesktopContextualWebPart.CustomPageComponent"", _addCustomPageComponent);
                }
                SP.SOD.executeOrDelayUntilScriptLoaded(_registerCustomPageComponent, ""sp.ribbon.js"");
                //]]>
                </script>";
            }

        }

        private void AddContextualTab()
        {
            //Gets the current instance of the ribbon on the page.
            Microsoft.Web.CommandUI.Ribbon ribbon = SPRibbon.GetCurrent(this.Page);

            //Prepares an XmlDocument object used to load the ribbon extensions.
            XmlDocument ribbonExtensions = new XmlDocument();

            //Load the contextual tab XML and register the ribbon extension.
            ribbonExtensions.LoadXml(this.contextualTab);
            ribbon.RegisterDataExtension(ribbonExtensions.FirstChild, "Ribbon.ContextualTabs._children");

            //Load the custom templates and register the ribbon extension.
            ribbonExtensions.LoadXml(this.contextualTabTemplate);
            ribbon.RegisterDataExtension(ribbonExtensions.FirstChild, "Ribbon.Templates._children");
        }
    }
}
